/*
* 作者: wupengxin
* 创建时间:
 */
package main

import (
	"github.com/howeyc/fsnotify"
	"log"
	"os"
	"path/filepath"
)

var sg_chan map[string]chan string= make(map[string] chan string)


func recursiveAddWatch(root string, watch *fsnotify.Watcher) (error) {
	root, _ = filepath.Abs(root)
	watch.Watch(root)
	err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
		if nil == fi {
			return err
		}
		if fi.IsDir() {
			println("add :", path)
			watch.RemoveWatch(path)
			watch.Watch(path)
		}
		return nil
	})

	return err
}

func main() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()


	done := make(chan bool)
	go func() {
		for {
			select {
			case event := <-watcher.Event:
			delete(sg_chan, "ssss")
				log.Println("event:", event)
				if event.IsModify() {
					log.Println("modified file:", event.Name)
				}
				if event.IsCreate(){
					println("create file:", event.Name)
					fi, _ := os.Stat(event.Name)
					if fi.IsDir(){
						watcher.Watch(event.Name)
					}else {
						//sg_file_env[event.Name] = make(chan string)

					}
				}
				if event.IsDelete(){
					println("delete file:", event.Name)
					watcher.RemoveWatch(event.Name)
				}
			case err := <-watcher.Error:
				log.Println("error:", err)
			}
		}
	}()

	//err = watcher.WatchFlags("/goproject/logpipe/src", fsnotify.FSN_CREATE|fsnotify.FSN_DELETE|fsnotify.FSN_MODIFY)
	err = recursiveAddWatch("./", watcher)
	if err != nil {
		log.Fatal(err)
	}
	<-done
}
